<?php

// 阿里云账户分组
class ImagesController extends AdminController
{
    // 列表
    public function listAction()
    {
        $do = $this->get('do');
        switch ($do) {
            case 'list':
                $parameters['conditions'] = array();
                $data = $this->_list(DunImagesModel::class, $parameters);
                foreach ($data['data'] as $item) {
                    $data_result[] = array(
                        'id' => $item->id,
                        'groupid' => $item->groupid,
                        'account' => $item->group->title,
                        'regionid' => $item->regionid,
                        'imageid' => $item->imageid,
                        'osname' => $item->osname,
                        'status' => $item->status,
                    );
                }
                $this->ajaxresult(0, '', $data_result, array('count' => $data['count']));
                break;
        }
    }

    // 创建镜像
    function createAction()
    {

    }

    // 更新镜像实例
    function refreshAction()
    {
        if ($this->ispost) {
            $groupid = $this->post('groupid');
            $regionid = $this->post('regionid');
            $account = DunGroupsModel::find($groupid);
            if ($account && $regionid) {
                $alibaba = new Aliyun($account->accessKeyId, $account->accessSecret);
                $alibaba->setRegion();
                $images = $alibaba->DescribeImages('system', 1, 100);
                if ($images && $images['TotalCount'] > 0) {
                    foreach ($images['Images']['Image'] as $item) {
                        $image = DunImagesModel::where([
                            'imageid' => $item['ImageId']
                        ])->find();
                        $data = [
                            'groupid' => $account->id,
                            'regionid' => $images['RegionId'],
                            'imageid' => $item['ImageId'],
                            'osname' => $item['OSName'],
                            'status' => $item['Status'],
                        ];
                        if ($image) {
                            $image->save($data);
                        } else {
                            DunImagesModel::create($data);
                        }
                    }
                }
                $this->ajaxresult(0, '操作成功');
            }
            $this->ajaxresult(1, '账户不存在');
        }
        // 加载所有地区
        $this->view->assign('all_regionid', Aliyun::getConfig('ecs'));
        // 加载所有账户
        $this->view->assign('all_account', DunGroupsModel::select());
    }
}